import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

import java.util.Vector;

public class SplashFileListThread implements Runnable
{
	private InputStream is;
	private SocketConnection sc;
	private SplashFileList sfl;
	private String url;
	private boolean error;
	private Vector rows;
	private StringBuffer current;
	private boolean first;
	
	public SplashFileListThread(String url, SplashFileList sfl)
	{
		this.url = url;
		this.sfl = sfl;
		this.error = false;
		this.first = false;
		this.rows = new Vector();
	}
	
	public void run()
	{
		try
		{
			this.sc = (SocketConnection) Connector.open(url);
			this.is = sc.openInputStream();	
						this.sfl.setTitle("Nalagam...");
			
			int b;
			this.current = new StringBuffer();
			String tstr = "";
			while((b = is.read()) != -1)
			{
				if(this.current.length() == 0 || !this.first)
				{
					if(b == '\r' || b == '\n')
					{
						this.first = true;
						continue;
					}
					
					this.current.append((char)b);
					continue;
				}
				
				if(!tstr.equals("") && (b == '\n' || b == '\r'))
				{
					this.rows.addElement(tstr);
					tstr = "";
				}
				
				if(b != '\n' && b != '\r')
					tstr += (char)b;
				
			}
			
			// add 'back'
			this.rows.addElement("d:..");
			
			this.sfl.done();
			
			this.is.close();
			this.sc.close();
		}
		catch(ConnectionNotFoundException cnfe)
		{
			this.error = true;
			this.sfl.setTitle("Ne morem vzpostaviti povezave.");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			/* Connection interrupted */
			this.error = true;
		}
		
		if(error)
		{
			this.sfl.setTitle("Napaka.");
		}
		
	}
	
	public boolean error()
	{
		return this.error;
	}
	
	public Vector getRows()
	{
		return this.rows;
	}
	
	public StringBuffer current()
	{
		return this.current;
	}

	public void connect()
	{
		new Thread(this).start();
	}
	
}
